package serviceimpl;

import entity.Order;
import entity.OrderDetail;
import entity.Product;
import entity.User;
import mapper.OrderDetailMapper;
import mapper.OrderMapper;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.OrderService;
import util.RedisUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;


    @Autowired
    RedisUtil redisUtil;

    @Transactional
public String createOrder(String userName){
     User user=userMapper.selectByUserName(userName);
     Order order=new Order();
     if(user!=null){
         order.setUserId(user.getId());
         order.setOrdernum(String.valueOf(System.currentTimeMillis()));
         //获取总价
         List<Object> list=redisUtil.lGet(userName,0,-1);//获取购物车
         Double price=0.0;
         for (int i = 0; i < list.size(); i++) {
             Product product=((Product) list.get(i));
             price+=product.getProductPrice()*product.getProductNum();
         }
         order.setTotalPrice(price);
         order.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
         order.setOrderStatus("0");//订单状态默认为0,属于待付款状态
         System.out.println("order===>"+order);
         int line=orderMapper.insertSelective(order);
         System.out.println("line===>>>"+line);
         List<OrderDetail> list2=new ArrayList<>();
         if(line>0){
             for (int i = 0; i < list.size(); i++) {
                 Product product=((Product) list.get(i));
                list2.add(new OrderDetail(order.getOid(),String.valueOf(product.getPid()),String.valueOf(product.getProductNum())));
             }
             int line2=orderDetailMapper.insertList(list2);
             if(line2>0){
                 return "ok";
             }
         }
     }
    return "no";
}




public String updateOrder(String userName){
    User user=userMapper.selectByUserName(userName);
         if(user!=null){
           Order order=orderMapper.getLastestOrder(user.getId());
           order.setOrderStatus("1");//状态改为1
           orderMapper.updateByPrimaryKey(order);
           return "ok";
         }
        return null;
}

public List<String> getOrderStatusNum(String userName){
        User user=userMapper.selectByUserName(userName);
        if(user!=null){
            return  orderMapper.getOrderStatusNum(user.getId());
        }

        return null;
}

}
